<template>
  <div class="permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleCreate">新增权限</el-button>
        </div>
      </template>
      
      <el-table 
        :data="permissions" 
        style="width: 100%" 
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="code" label="权限编码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 权限表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionFormRules"
        label-width="80px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" />
        </el-form-item>
        <el-form-item label="父级权限" prop="parent_id">
          <el-select v-model="permissionForm.parent_id" placeholder="请选择父级权限" clearable style="width: 100%">
            <el-option
              v-for="item in parentPermissions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="permissionForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="permissionForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissionTree, createPermission, updatePermission, deletePermission } from '@/api/permission'

// 权限数据
const permissions = ref([])
const parentPermissions = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单引用
const permissionFormRef = ref()

// 权限表单数据
const permissionForm = reactive({
  id: 0,
  name: '',
  code: '',
  parent_id: null,
  description: '',
  status: 1
})

// 表单验证规则
const permissionFormRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' }
  ]
}

// 获取权限树
const fetchPermissions = async () => {
  loading.value = true
  try {
    const res: any = await getPermissionTree()
    
    if (res.success) {
      permissions.value = res.data
      // 构建父级权限选项（排除当前编辑的权限及其子权限）
      parentPermissions.value = buildParentPermissions(res.data)
    } else {
      ElMessage.error(res.message || '获取权限列表失败')
    }
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 构建父级权限选项
const buildParentPermissions = (data: any[], excludeId?: number) => {
  const result: any[] = []
  
  const traverse = (items: any[]) => {
    for (const item of items) {
      if (item.id !== excludeId) {
        result.push({
          id: item.id,
          name: item.name
        })
      }
      
      if (item.children && item.children.length > 0) {
        traverse(item.children)
      }
    }
  }
  
  traverse(data)
  return result
}

// 处理新增
const handleCreate = () => {
  dialogTitle.value = '新增权限'
  isEdit.value = false
  // 重置表单
  Object.assign(permissionForm, {
    id: 0,
    name: '',
    code: '',
    parent_id: null,
    description: '',
    status: 1
  })
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑权限'
  isEdit.value = true
  // 填充表单数据
  Object.assign(permissionForm, row)
  // 更新父级权限选项（排除当前编辑的权限及其子权限）
  parentPermissions.value = buildParentPermissions(permissions.value, row.id)
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除权限 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res: any = await deletePermission(row.id)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchPermissions()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitForm = async () => {
  if (!permissionFormRef.value) return
  
  await permissionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res: any
        if (isEdit.value) {
          // 编辑
          res = await updatePermission(permissionForm.id, {
            name: permissionForm.name,
            code: permissionForm.code,
            parent_id: permissionForm.parent_id,
            description: permissionForm.description,
            status: permissionForm.status
          })
        } else {
          // 新增
          res = await createPermission({
            name: permissionForm.name,
            code: permissionForm.code,
            parent_id: permissionForm.parent_id,
            description: permissionForm.description,
            status: permissionForm.status
          })
        }
        
        if (res.success) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchPermissions()
        } else {
          ElMessage.error(res.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPermissions()
})
</script>

<style scoped>
.permission-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>